package com.p2l.letterblocks;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

public class Server {
	public static final String[] FOLDERS = new String[] { "hats/", "shirts/", "pants/", "belts/", "accessories/", "chapters/" };
	public static final String URL_CHAPTER_TRANSACTIONS = "http://letterblocks.nestor.dk/select_chapter_transactions.asp";
	public static final String URL_LEVELS_COMPLETED = "http://letterblocks.nestor.dk/select_levels_completed.asp";
	public static final String URL_CHAPTER_BOUGHT = "http://letterblocks.nestor.dk/select_chapter_bought.asp";
	public static final String URL_USER_CHAPTERS = "http://letterblocks.nestor.dk/select_user_chapters.asp";
	public static final String URL_USER_ITEMS = "http://letterblocks.nestor.dk/select_user_items.asp";
	public static final String URL_COIN_SCORE = "http://letterblocks.nestor.dk/select_coin_score.asp";
	public static final String URL_DAILY_COIN = "http://letterblocks.nestor.dk/select_daily_coin.asp";
	public static final String URL_CHAPTERS = "http://letterblocks.nestor.dk/select_chapters.asp";
	public static final String URL_ITEM_BOUGHT = "http://letterblocks.nestor.dk/select_item.asp";
	public static final String URL_OBJECTS = "http://letterblocks.nestor.dk/select_objects.asp";
	public static final String URL_VERSION = "http://letterblocks.nestor.dk/select_version.asp";
	public static final String URL_LEVELS = "http://letterblocks.nestor.dk/select_levels.asp";
	public static final String URL_ITEMS = "http://letterblocks.nestor.dk/select_items.asp";
	public static final String URL_USERS = "http://letterblocks.nestor.dk/select_users.asp";
	public static final String URL_LOGIN = "http://letterblocks.nestor.dk/select_login.asp";

	public static final String URL_INSERT_COIN_TRANSACTION = "http://letterblocks.nestor.dk/insert_coin_transaction.asp";
	public static final String URL_INSERT_LEVEL_COMPLETED = "http://letterblocks.nestor.dk/insert_levels_completed.asp";
	public static final String URL_OFFLINE_LOGINS = "http://letterblocks.nestor.dk/insert_offline_logins.asp";
	public static final String URL_INSERT_DAILY_COIN = "http://letterblocks.nestor.dk/insert_daily_coin.asp";
	public static final String URL_BUY_CHAPTER = "http://letterblocks.nestor.dk/insert_chapter.asp";
	public static final String URL_INSERT_LOGIN = "http://letterblocks.nestor.dk/insert_login.asp";
	public static final String URL_CREATE_USER = "http://letterblocks.nestor.dk/insert_user.asp";
	public static final String URL_BUY_ITEM = "http://letterblocks.nestor.dk/insert_item.asp";
	
	public static final String URL_UPDATE_LEVEL_COMPLETED = "http://letterblocks.nestor.dk/update_levels_completed.asp";
	
	public static final String URL_HOME = "http://letterblocks.nestor.dk/";
	public static final String URL = "http://letterblocks.nestor.dk/";
	
	public static final String FOLDER = "letterblocks";
	
	public static InputStream open(String urlString) throws IOException {
		InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                  
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
 
            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");           
        }
        return in; 
    }
	
	public static XmlPullParser toXmlParser(InputStream in) throws XmlPullParserException {
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    	parser.setInput(in, "UTF-8");
		return parser;
	}
	
	public static Bitmap downloadBitmap(InputStream in)
    {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
        	e.printStackTrace();
        } catch (OutOfMemoryError e) {
        	e.printStackTrace();
        }
        return bitmap;               
    }
	
	public static boolean saveBitmap(Context context, String folder, String name, Bitmap b) {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			try {
				File dir = new File(Environment.getExternalStorageDirectory() + "/" + FOLDER + "/" + folder);
				if (!dir.exists()) {
					dir.mkdirs();
				}
					
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
					
				File file = new File(Environment.getExternalStorageDirectory() + "/" + FOLDER + "/" + folder, name);
				file.createNewFile();
					
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(bytes.toByteArray());
					
				fos.close();
				return true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
				return false;
			}
		} else {
			Log.e("LetterBlocks", "SD card not ready");
			return false;
		}
	}
	
	public static Bitmap loadBitmap(Context context, String folder, String name) {
		try {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inScaled = false;
				return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + FOLDER + "/" + folder + "/" + name, options);
			}
		} catch (OutOfMemoryError e) { }
		return null;
	}
	
	public static boolean saveSoundFile(Context context, InputStream in, String folder, String name) {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			try {
				File dir = new File(Environment.getExternalStorageDirectory() + "/" + FOLDER + "/" + folder);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				
				File file = new File(Environment.getExternalStorageDirectory() + "/" + FOLDER + "/" + folder, name);
				FileOutputStream fos = new FileOutputStream(file);
				
				byte[] buffer = new byte[1024];
				int len = 0;
				
				while ((len = in.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fos.close();
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
	
	public static void runAsyncTask(Activity activity, String sql) {
		final String task = sql;
		activity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				new Server.ServerTask().execute(task);
			}
		});
	}
	
	public static class ServerTask extends AsyncTask<String, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(String... params) {
			try {
				InputStream in = Server.open(params[0]);
				in.close();
			} catch (IOException e) {
				Log.e("LetterBlocks", e.toString());
				return false;
			}
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	this.cancel(true);
	    }
	}
}
